package com.jl.core.service.impl;

import com.jl.core.mapper.UserMapper;
import com.jl.core.service.UserService;
import com.jl.exception.RRException;
import com.jl.model.User;
import com.jl.model.vo.UserVo;
import com.jl.service.GetUserInfoService;
import com.jl.utils.UserInfoContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@Transactional
public class UserServiceImpl implements UserService {

    @Resource
    private RedisTemplate redisTemplate;
    private String code = "123456";
    @Resource
    private UserMapper userMapper;
    @Autowired
    private GetUserInfoService getUserInfoService;

    @Override
    public void getCode(String phone) {
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);
    }

    @Override
    public void bindPhone(String phone, String code, String password, String password2) {
        if (!password.equals(password2)){
            throw new RRException("2次密码输入不一样","501");
        }
        String s = redisTemplate.opsForValue().get(phone).toString();
        if (!s.equals(code)){
            throw new RRException("验证码错误","501");
        }
        UserVo user = UserInfoContext.getUser();
        List<User> users = userMapper.selectUserByPhone(phone);
        if (users.size()>0){
            throw new RRException("此手机号已被绑定","501");
        }
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        user1.setPhone(phone);
        user1.setPassword(getUserInfoService.encrypt(password));
        getUserInfoService.setUserToRedis(user1);
        userMapper.updateByPrimaryKeySelective(user1);
    }
}
